package com.neiquan.neiquandemo.utils;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.neiquan.neiquandemo.appliction.MyApplication;

import net.neiquan.applibrary.R;
import net.neiquan.applibrary.utils.GlideUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * =================================================================================================
 * |
 * |    what:    底部导航栏
 * |
 * |    --------------------------------------------------------------------------------------------
 * |
 * |    who:     wall
 * |    when:    2017/5/9 16:07
 * |
 * =================================================================================================
 */
public class BottomLayout extends LinearLayout {

    private ViewPager mViewPager;
    //所有Tab真实视图
    private List<TabView> mTabs;
    //当前选择项
    private int currentPosition = 0;
    //上一次选择项，默认为0
    private int lastPosition = currentPosition;
    //Tab点击监听器
    private OnTabSelectListener onTabSelectListener;

    public BottomLayout(Context context) {
        this(context, null);
    }

    public BottomLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //设置横向布局
        setOrientation(HORIZONTAL);
        //设置布局居中排布
        setGravity(Gravity.CENTER);
//        setPadding(0, DensityUtils.dp2px(context, 6), 0, DensityUtils.dp2px(context, 10));
        //设置布局最小高度
        setMinimumHeight(dp2px(45));
        mTabs = new ArrayList<>();
    }

    /**
     * 添加Tab
     *
     * @param tab
     */
    public void addTab(Tab tab) {
        if (tab != null) {
            addTab(tab, mTabs.size());
        } else {
            addTab(new Tab(), false);
        }
    }

    public List<TabView> getmTabs() {
        return mTabs;
    }

    public int getTabsCount(){return  mTabs.size();}

    public void setmTabs(List<TabView> mTabs) {
        this.mTabs = mTabs;
    }

    /**
     * 添加Tab
     *
     * @param tab
     * @param visible 是否可见
     */
    public void addTab(Tab tab, boolean visible) {
        addTab(tab, mTabs.size(), visible, false);
    }

    /**
     * 添加Tab到指定位置
     *
     * @param tab
     * @param position
     */
    public void addTab(Tab tab, int position) {
        addTab(tab, position, false);
    }

    /**
     * 添加Tab到指定位置，并指定是否选中
     *
     * @param tab
     * @param position
     * @param isSelected
     */
    public void addTab(Tab tab, int position, boolean isSelected) {
        addTab(tab, position, true, isSelected);
    }

    /**
     * 添加Tab
     *
     * @param tab
     * @param position
     * @param visible
     * @param isSelected
     */
    public void addTab(Tab tab, int position, boolean visible, boolean isSelected) {
        if (tab == null) {
            tab = new Tab();
        }
        tab.setPosition(position);
        tab.setSelected(isSelected);
        TabView tabView = createTabView(tab);

        addView(tabView);

        if (visible) {
            mTabs.add(tabView);
        } else {
            tabView.setVisibility(View.INVISIBLE);
            Log.d("Tab","Tab");
        }
        if(tab.getBig()==1)
        {
            tabView.showBig(true);
        }


        tabView.hideText(tab.getHideText());

    }

    @Override
    public void addView(View child, ViewGroup.LayoutParams params) {
        // 设置真实容器的布局属性
        LayoutParams lp = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
        // 在父容器中均匀分布的必要
        lp.weight = 1;
        super.addView(child, lp);
    }

    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        // 设置真实容器的布局属性
        LayoutParams lp = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
        // 在父容器中均匀分布的必要
        lp.weight = 1;
        super.addView(child, index, lp);
    }

    /**
     * 设置当前选择项
     *
     * @param currentPosition
     */
    public void setCurrentPosition(int currentPosition) {
        try {
            //更新上一选择项
            this.lastPosition = this.currentPosition;
            //更新当前选择项
            this.currentPosition = currentPosition;
            if(mTabs.size()>this.lastPosition){
                //取消上一选择项
                mTabs.get(lastPosition).setUnSelected();
                //选中当前选择项
                mTabs.get(currentPosition).setSelected();
                if (mViewPager != null) {
                    mViewPager.setCurrentItem(currentPosition);
                }
            }
        }catch (Exception e){}
    }

    /**
     * 绑定Tab选择监听器
     *
     * @param onTabSelectListener
     */
    public void setOnTabSelectListener(OnTabSelectListener onTabSelectListener) {
        this.onTabSelectListener = onTabSelectListener;
    }

    public void setUp(int position) {
        setCurrentPosition(position);
        mTabs.get(position).onTabClick();
    }

    public void setUpWithViewPager(ViewPager viewPager) {
        mViewPager = viewPager;
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                setCurrentPosition(position);
            }
        });
    }


    public TabView getTabView(int position) {
        return mTabs.get(position);
    }

    public void showTip(boolean isShow)
    {
        if(null !=mTabs && mTabs.size() > 0){
            mTabs.get(mTabs.size()-1).showNotice(isShow);
        }
    }

    /**
     * 创建一个新的Tab视图
     *
     * @param tab
     * @return
     */
    private TabView createTabView(Tab tab) {
        TabView tabView = new TabView(getContext());
        tabView.setTab(tab);
        return tabView;
    }

    public interface ITabView {

        /**
         * 设置当前Tab视图为选中状态
         */
        void setSelected();

        /**
         * 取消当前Tab视图选中状态
         */
        void setUnSelected();
    }

    @Nullable
    @Override
    protected Parcelable onSaveInstanceState() {

        Parcelable parcelable = super.onSaveInstanceState();
        SavedState ss = new SavedState(parcelable);
        ss.position = currentPosition;
        ss.lastPosition = lastPosition;
        return ss;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        try {
            SavedState ss = (SavedState) state;
            super.onRestoreInstanceState(ss.getSuperState());
            setCurrentPosition(ss.position);
            mTabs.get(ss.position).onTabClick();
            lastPosition = ss.lastPosition;
        }catch (Exception e){}
    }

    static class SavedState extends BaseSavedState {
        int position;
        int lastPosition;

        SavedState(Parcelable superState) {
            super(superState);
        }

        /**
         * Constructor called from {@link #CREATOR}
         */
        private SavedState(Parcel in) {
            super(in);
            position = in.readInt();
            lastPosition = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(position);
            out.writeInt(lastPosition);
        }

        public static final Creator<SavedState> CREATOR
                = new Creator<SavedState>() {
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

    /**
     * Tab视图
     */
    public class TabView extends ConstraintLayout implements ITabView {
        //绑定的Tab内容
        private Tab mTab;
        //Tab图标
        private AppCompatImageView mTabImage;
        //Tab 大图标
        private AppCompatImageView mTabBigImage;
        private ImageView image_view1;
        //Tab文字
        private AppCompatTextView mTabText;

        private RelativeLayout rl_view;

        private View view11;

        private AppCompatTextView mTabNotice;
        //取消点击事件，防止长按拖动
        private boolean isCancel = false;

        public Tab getmTab() {
            return mTab;
        }

        public void setmTab(Tab mTab) {
            this.mTab = mTab;
        }

        public TabView(Context context) {
            super(context);
            LayoutInflater.from(context).inflate(R.layout.tab_view, this);
            // 设置点击波纹
            TypedValue typedValue = new TypedValue();
            getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true);
            int[] attribute = new int[]{android.R.attr.selectableItemBackground};
            TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(typedValue.resourceId, attribute);
//
            mTabImage = this.findViewById(R.id.image_view);
//            mTabImage.setLayoutParams(new ViewGroup.LayoutParams(dp2px(33),
//                    dp2px(33)));
            mTabText = this.findViewById(R.id.text_view);
            view11 = this.findViewById(R.id.view11);
//            mTabText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
//                    ViewGroup.LayoutParams.WRAP_CONTENT));

//            addView(mTabImage);
//            addView(mTabText);
            mTabNotice=this.findViewById(R.id.text_msg_volume);

            mTabBigImage=this.findViewById(R.id.image_view_big);
            image_view1=this.findViewById(R.id.image_view1);
            rl_view=this.findViewById(R.id.rl_view);

            //Tab点击事件，用于更新选中和未选中状态
            this.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    onTabClick();
                }
            });
        }

        /**
         * 设置Tab
         *
         * @param tab
         */
        private void setTab(Tab tab) {
            mTab = tab;
            update();
        }
        public void showNotice(boolean isShow)
        {
            if(isShow) {
                mTabNotice.setVisibility(VISIBLE);
            }else {
                mTabNotice.setVisibility(GONE);
            }
        }
        public void showBig(boolean isShow)
        {
            if(isShow) {
                mTabBigImage.setVisibility(VISIBLE);
                mTabImage.setVisibility(INVISIBLE);
                mTabText.setTextSize(getResources().getDimensionPixelSize(R.dimen.textsiz_16px));
                TextPaint tp = mTabText.getPaint();
                tp.setFakeBoldText(true);
            }else {
                mTabBigImage.setVisibility(GONE);
            }
        }

        public void hideText(int hide){
            if (hide == 0){
                image_view1.setVisibility(GONE);
                rl_view.setVisibility(VISIBLE);
            }else {
                image_view1.setVisibility(VISIBLE);
                rl_view.setVisibility(GONE);
                mTabBigImage.setVisibility(GONE);
            }
        }

        /**
         * 更新Tab
         */
        public void update() {
//            mTabText.setTextSize(mTab.getTextSize());
            if (!TextUtils.isEmpty(mTab.getText())) {
                mTabText.setText(mTab.getText());
            }
            if (mTab.getTextColor() != 0) {
                mTabText.setTextColor(getContext().getResources().getColor(mTab.getTextColor()));
            }
            if (mTab.getImgResId() != 0) {
                mTabImage.setImageResource(mTab.getImgResId());
                mTabBigImage.setImageResource(mTab.getImgResId());
                image_view1.setImageResource(mTab.getImgResId());
            }
            else
            {
                if(mTab.getType()==1) {
                    GlideUtil.displayImg(mTab.getImgResUrl(), mTabImage);
                    GlideUtil.displayImg(mTab.getImgResUrl(), mTabBigImage);
                    GlideUtil.displayImg(mTab.getImgResUrl(), image_view1);
                }
                else
                {
                    Uri uri;
                    if (Build.VERSION.SDK_INT >= 24) {
                        uri = FileProvider.getUriForFile(getContext(), MyApplication.fileProvider, new File(mTab.getImgResUrl()));
                    } else {
                        uri = Uri.fromFile(new File(mTab.getImgResUrl()));
                    }


                    //Glide.with(mTabImage.getContext()).load(new File(mTab.getImgResUrl())).into(mTabImage);
                    mTabImage.setImageURI(uri);
                    mTabBigImage.setImageURI(uri);
                    image_view1.setImageURI(uri);
                    //本地文件
                    /*File file = new File(mTab.getImgResUrl());
                    Glide.with(this).load(file).into(mTabImage);*/
                }
            }
            mTab.setSelected(false);
        }

        @Override
        public void setSelected() {
//            setPadding(0, dp2px(8), 0, dp2px(10));
//            mTabText.setTextSize(mTab.getFocusTextSize());

            if (!TextUtils.isEmpty(mTab.getText())) {
                mTabText.setText(mTab.getText());
            }
            if (mTab.getFocusTextColor() != 0) {
                mTabText.setTextColor(getContext().getResources().getColor(mTab.getFocusTextColor()));
            }
            if (mTab.getFocusImgResId() != 0) {
                mTabImage.setImageResource(mTab.getFocusImgResId());
                mTabBigImage.setImageResource(mTab.getFocusImgResId());
                image_view1.setImageResource(mTab.getFocusImgResId());
            }
            else
            {
                if(mTab.getType()==1) {
                    GlideUtil.displayImg(mTab.getFocusImgResUrl(), mTabImage);
                    GlideUtil.displayImg(mTab.getFocusImgResUrl(), mTabBigImage);
                    GlideUtil.displayImg(mTab.getFocusImgResUrl(), image_view1);
                }
                else
                {
                    Uri uri;
                    if (Build.VERSION.SDK_INT >= 24) {
                        uri = FileProvider.getUriForFile(getContext(), MyApplication.fileProvider, new File(mTab.getFocusImgResUrl()));
                    } else {
                        uri = Uri.fromFile(new File(mTab.getFocusImgResUrl()));
                    }
                    mTabImage.setImageURI(uri);
                    mTabBigImage.setImageURI(uri);
                    image_view1.setImageURI(uri);
                }
            }
            mTab.setSelected(true);
        }

        @Override
        public void setUnSelected() {
//            setPadding(0, dp2px(6), 0, dp2px(10));
            update();
        }

        /**
         * 处理Tab点击事件
         */
        private void onTabClick() {
            setCurrentPosition(mTab.getPosition());
            if (onTabSelectListener != null) {
                onTabSelectListener.onTabSelected(mTab);
            }
            if (image_view1!=null){
                ObjectAnimator scaleX = ObjectAnimator.ofFloat(image_view1,"scaleX",0.7f,1f);
                ObjectAnimator scaleY = ObjectAnimator.ofFloat(image_view1,"scaleY",0.7f,1f);
                AnimatorSet animatorSet1 = new AnimatorSet();
                animatorSet1.play(scaleX).with(scaleY);
                animatorSet1.setDuration(500);
                animatorSet1.start();
            }
        }

        public void setView11(boolean isGone) {
            if (view11 != null) {
                if (isGone){
                    view11.setVisibility(VISIBLE);
                }else {
                    view11.setVisibility(GONE);
                }
            }
        }
        public void setTextColor(int color) {
            if (mTabText != null) {
                mTabText.setTextColor(color);
            }
        }

//        @Override
//        public boolean performClick() {
//            boolean handled = super.performClick();
//            if (mTab!=null){
//                if (!handled){
//                    playSoundEffect(SoundEffectConstants.CLICK);
//                }
//                mTab.setSelected(true);
//                return true;
//            }
//            return handled;
//        }

    }

    /**
     * Tab内容
     */
    public static class Tab {

        private String text;

        private int imgResId=0;
        private int focusImgResId=0;


        private String imgResUrl;
        private String focusImgResUrl;

        private int textColor;
        private int focusTextColor;

        private int textSize = 10;
        private int focusTextSize = 10;

        private boolean isSelected = false;
        private int position = 0;
        private int type=0;//0 本地 1网络

        private int big=0;//0 小  1大

        private int hideText = 0;//1隐藏  0显示

        public Tab() {
        }





        public Tab(String text, @DrawableRes int imgResId) {
            this.text = text;
            this.imgResId = imgResId;

            this.focusImgResId = imgResId;
        }

        public Tab(String text, int imgResId, int focusImgResId) {
            this.text = text;
            this.imgResId = imgResId;
            this.focusImgResId = focusImgResId;
        }

        public Tab(String text,
                   @DrawableRes int imgResId,
                   @DrawableRes int focusImgResId,
                   int textColor,
                   int focusTextColor,
                   int big) {
            this.text = text;
            this.imgResId = imgResId;
            this.focusImgResId = focusImgResId;
            this.textColor = textColor;
            this.focusTextColor = focusTextColor;
            this.big=big;
        }
        public Tab(String text,int type,
                   String imgResUrl,
                   String  focusImgResUrl,
                   int textColor,
                   int focusTextColor,
                   int big,
                   int hideText) {
            this.text = text;
            this.imgResUrl = imgResUrl;
            this.focusImgResUrl = focusImgResUrl;
            this.textColor = textColor;
            this.focusTextColor = focusTextColor;
            this.type=type;
            this.big=big;
            this.hideText=hideText;
        }

        public void setFocusImgResId(int focusImgResId) {
            this.focusImgResId = focusImgResId;
        }

        public void setImgResId(int imgResId) {
            this.imgResId = imgResId;
        }

        public void setFocusTextColor(int focusTextColor) {
            this.focusTextColor = focusTextColor;
        }

        public String getText() {
            return text;
        }

        public int getImgResId() {
            return imgResId;
        }

        public int getFocusImgResId() {
            return focusImgResId;
        }

        public int getTextColor() {
            return textColor;
        }

        public int getFocusTextColor() {
            return focusTextColor;
        }

        public void setPosition(int position) {
            this.position = position;
        }

        public int getPosition() {
            return position;
        }

        public void setSelected(boolean selected) {
            isSelected = selected;
        }

        public int getTextSize() {
            return textSize;
        }

        public void setTextSize(int textSize) {
            this.textSize = textSize;
        }

        public int getFocusTextSize() {
            return focusTextSize;
        }

        public void setFocusTextSize(int focusTextSize) {
            this.focusTextSize = focusTextSize;
        }

        public boolean isSelected() {
            return isSelected;
        }
        public String getImgResUrl() {
            return imgResUrl;
        }

        public void setImgResUrl(String imgResUrl) {
            this.imgResUrl = imgResUrl;
        }

        public String getFocusImgResUrl() {
            return focusImgResUrl;
        }

        public void setFocusImgResUrl(String focusImgResUrl) {
            this.focusImgResUrl = focusImgResUrl;
        }
        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }
        public int getBig() {
            return big;
        }

        public void setBig(int big) {
            this.big = big;
        }

        public int getHideText() {
            return hideText;
        }

        public void setHideText(int hideText) {
            this.hideText = hideText;
        }
    }

    public interface OnTabSelectListener {
        void onTabSelected(Tab tab);
    }

    private int dp2px(float dpValue) {
        float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

}